﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace App1
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            Loaded += MainPage_Loaded;
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            RightHandleText.Text = Text((RightHandle.RenderTransform as CompositeTransform).TranslateX);
            LeftHandleText.Text = Text((LeftHandle.RenderTransform as CompositeTransform).TranslateX);
        }

        int Min = 0;
        int Max = 100;
        int Size = 100;
        int Range = 200;

        private void LeftHandle_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
        {
            var t = (sender as Grid).RenderTransform as CompositeTransform;
            var x = (RightHandle.RenderTransform as CompositeTransform).TranslateX;
            var f = -this.Range;
            var c = x - this.Size * .5;
            t.TranslateX = Translate(t, e, f, c);
            LeftHandleText.Text = Text(t.TranslateX);
        }

        private void RightHandle_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
        {
            var t = (sender as Grid).RenderTransform as CompositeTransform;
            var x = (LeftHandle.RenderTransform as CompositeTransform).TranslateX;
            var f = x + this.Size * .5;
            var c = this.Range;
            t.TranslateX = Translate(t, e, f, c);
            RightHandleText.Text = Text(t.TranslateX);
        }

        private double Translate(CompositeTransform s, ManipulationDeltaRoutedEventArgs e, double floor, double ceiling)
        {
            var target = s.TranslateX + e.Delta.Translation.X;
            if (target < floor)
                return floor;
            if (target > ceiling)
                return ceiling;
            return target;
        }

        private string Text(double x)
        {
            var p = (x - (-this.Range)) / ((this.Range) - (-this.Range)) * 100d;
            var v = (this.Max - this.Min) * p / 100d + this.Min;
            return ((int)v).ToString();
        }
    }
}
